import axios from 'axios'
import qs from 'qs'
import config from '@/config'
import store from '@/store/'
import md5 from 'md5'
import randomatic from 'randomatic'

axios.defaults.baseURL = config.host.api
// axios.defaults.timeout = 1000 * 60 * 5
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.paramsSerializer = (params) => qs.stringify(params, {arrayFormat: 'repeat'})
// axios.defaults.transformRequest = [v => qs.stringify(v)]

axios.interceptors.request.use((conf) => {
  conf.headers.Accept = 'application/json'

  const token = store.state.authorization.token || ''
  const timestamp = store.state.system.now
  const nonsense = randomatic('Aa0', 32)
  const device = store.state.authorization.device || ''

  conf.headers['Access-Control-TK'] = token
  conf.headers['Access-Control-TS'] = timestamp
  conf.headers['Access-Control-DV'] = device
  conf.headers['Access-Control-NS'] = nonsense
  conf.headers['Access-Control-SG'] = md5([timestamp, device, token, nonsense].sort().join('YM'))

  return conf
}, (error) => {
  // Do something with request error
  // return Promise.reject(error)
  return error
})
axios.interceptors.response.use((res) => {
  if (res.data && res.data.success === false) {
    throw res.data
  }

  return res.data
}, function (res) {
  const status = (res.response || res).status

  console.log('axios requset fail', res.response || res)

  if (status === 401) {
    window.toLogin()
    /* eslint-disable no-throw-literal */
    throw null
  }

  if (!(res instanceof Error)) {
    // 非Error返回
  } else if (res.message === 'Network Error') {
    throw new Error('请求失败，有可能正在重启服务，请稍后重试')
  } else {
    throw res && res.response && res.response.data ? res.response.data : res
  }

  if (!res.response) return

  if (status === 422) {
    throw res.response.data
  }
  if (status === 423) {
    throw res.response.data
  }
  if (status === 403) {
    // window.redirect({name: 'no-permission'})
  }
  if (status === 404 && res.response.success === undefined) {
    throw new Error('请求失败请检查URL是否正确')
  }
  if (res.response.data) {
    throw res.response.data
  }
  if (status >= 500) {
    throw new Error('服务器处理失败、请稍候再试或联系管理员')
  }

  throw res
})
